<?php
class Site extends Record {

    public function setTableDefinition() {
        $this->setTableName("sites");
        
        $this->hasColumn("id", "integer", array( "unsigned" => TRUE, "autoincrement" => TRUE, "primary" => TRUE ));
        $this->hasReferenceColumn("url_id", TRUE);
        $this->hasColumn("last_update_time", "integer");
    }

    public function setUp() {
        $this->hasMany("Stream as streams", array(
            "local" => "id",
            "foreign" => "site_id"
        ) );

        $this->hasOne("Url as url", array(
            "local" => "url_id",
            "foreign" => "id",
            "onDelete" => "CASCADE"
        ) );
        
    }

    public function setLastUpdate( $time ) {
        $this->last_update_time = $time;
        return $this;
    }

    public function setUrl( Url $url ) {
        $this->url = $url;
        return $this;
    }

    public function getUrl() {
        return $this->url->getUrl();
    }

}

class SiteTable extends Doctrine_Table {

    public function getByUrl( $url ) {
        $site = $this->findByUrl( $url );

        if ( !$site ) {
            $site = new Site();
            $site->setUrl( Doctrine::getTable("Url")->getByUrl( $url ) )
                 ->save();
        }

        return $site;
    }

    public function findByUrl( $url) {
        $url = Doctrine::getTable("Url")->findOneByUrl($url);

        if ( $url ) {
            $site = $this->findOneByUrlId( $url );

            if ( $site ) {
                return $site;
            }
        }

        return FALSE;
    }

}